/**
 * 通用AJAX请求函数
 * @param {string} url - 请求URL
 * @param {string} method - 请求方法
 * @param {Object} data - 请求数据
 * @param {Function} successCallback - 成功回调
 * @param {Function} errorCallback - 失败回调
 */
function ajaxRequest(url, method, data, successCallback, errorCallback) {
    fetch(url, {
        method: method,
        headers: {
            'Content-Type': 'application/json'
        },
        body: data ? JSON.stringify(data) : null
    })
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(data => {
            if (successCallback) successCallback(data);
        })
        .catch(error => {
            console.error('Error:', error);
            if (errorCallback) errorCallback(error);
        });
}

/**
 * 初始化表格数据
 * @param {string} tableId - 表格ID
 * @param {string} apiUrl - API URL
 * @param {Array} columns - 列配置
 */
function initTable(tableId, apiUrl, columns) {
    const table = document.getElementById(tableId);
    const tbody = table.querySelector('tbody');

    ajaxRequest(apiUrl, 'GET', null,
        (data) => {
            tbody.innerHTML = '';
            data.forEach(item => {
                const tr = document.createElement('tr');
                columns.forEach(column => {
                    const td = document.createElement('td');
                    if (column.render) {
                        td.innerHTML = column.render(item);
                    } else {
                        td.textContent = item[column.field] || '';
                    }
                    tr.appendChild(td);
                });
                tbody.appendChild(tr);
            });
        },
        (error) => {
            alert('获取数据失败: ' + error.message);
        }
    );
}

/**
 * 显示模态框
 * @param {string} modalId - 模态框ID
 */
function showModal(modalId) {
    const modal = document.getElementById(modalId);
    modal.classList.add('show');
    modal.style.display = 'block';
}

/**
 * 隐藏模态框
 * @param {string} modalId - 模态框ID
 */
function hideModal(modalId) {
    const modal = document.getElementById(modalId);
    modal.classList.remove('show');
    modal.style.display = 'none';
}

/**
 * 表单验证
 * @param {HTMLFormElement} form - 表单元素
 * @returns {boolean} - 验证结果
 */
function validateForm(form) {
    let isValid = true;
    const inputs = form.querySelectorAll('input[required], select[required]');
    inputs.forEach(input => {
        if (!input.value.trim()) {
            isValid = false;
            input.classList.add('is-invalid');
        } else {
            input.classList.remove('is-invalid');
        }
    });
    return isValid;
}
    